package com.mingqijia.gassafety.console.controller.inner;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gap.basic.exception.BizException;
import com.github.pagehelper.PageHelper;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.entity.Consumer;
import com.mingqijia.gassafety.db.entity.ConsumerLocation;
import com.mingqijia.gassafety.db.entity.Dictionary;
import com.mingqijia.gassafety.db.entity.FieldTemplate;
import com.mingqijia.gassafety.db.entity.auth.CompanyEntry;
import com.mingqijia.gassafety.db.mapper.ConsumerLocationMapper;
import com.mingqijia.gassafety.db.mapper.ConsumerMapper;
import com.mingqijia.gassafety.db.mapper.FieldTemplateMapper;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.CustStatusEnum;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.LocationUtil;
import com.mingqijia.gassafety.webserver.response.VccUserRseponse;
import com.mingqijia.gassafety.webserver.service.CompanyService;
import com.mingqijia.gassafety.webserver.service.ConsumerLocationService;
import com.mingqijia.gassafety.webserver.service.ConsumerService;
import com.mingqijia.gassafety.webserver.service.DictionaryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: duanhongxiang
 * @Date: 2024/4/18 15:03
 */
@Slf4j
@Api(tags = "地图数据处理")
@RestController(value = "ConsumerMapController")
@RequestMapping("/inner/v1/map")
public class ConsumerMapController {
    @Resource
    ConsumerLocationMapper consumerLocationsMapper;

    @Resource
    FieldTemplateMapper fieldTemplateMapper;

    @Resource
    ConsumerLocationService consumerLocationService;

    @Resource
    ConsumerService consumerService;

    @Resource
    CompanyService companyService;

    @Resource
    ConfigureHolder holder;

    @Resource
    DictionaryService dictionaryService;

    @Autowired
    LocationUtil locationUtil;

    @ApiOperation("设备详情")
    @RequestMapping(value = "/handleData", method = RequestMethod.GET)
    public void handleCustomData(@RequestParam("spId") String spId,
                                 @RequestParam("page") Integer page,
                                 @RequestParam("pageSize") Integer pageSize) {
        LambdaQueryWrapper<FieldTemplate> fieldTemplateQueryWrapper = new LambdaQueryWrapper<>();
        fieldTemplateQueryWrapper.eq(FieldTemplate::getFuncAreaAllocat,2);
        fieldTemplateQueryWrapper.eq(FieldTemplate::getIsDeleted, 0);
        List<FieldTemplate> fieldTemplates = fieldTemplateMapper.selectList(fieldTemplateQueryWrapper);
        List<String> spIds = fieldTemplates.stream().map(FieldTemplate::getSpId).collect(Collectors.toList());

        LambdaQueryWrapper<ConsumerLocation> queryWrapper = new LambdaQueryWrapper();
        if( !"0".equals(spId) ){
            queryWrapper.eq(ConsumerLocation::getSpId,spId);
        }
        queryWrapper.gt(ConsumerLocation::getLng,0);
        queryWrapper.gt(ConsumerLocation::getLat,0);
        //queryWrapper.isNull(ConsumerLocation::getAdcode);
        if (!spIds.isEmpty()){
            queryWrapper.notIn(ConsumerLocation::getSpId, spIds);
        }
        PageHelper.startPage(page, pageSize);
        List<ConsumerLocation> consumerList = consumerLocationsMapper.selectList(queryWrapper);
        log.info("共查询{}条数据",consumerList.size());
        int cnt = 0;
        for (ConsumerLocation consumerLocation:consumerList) {
            JSONObject resultJson = locationUtil.baiDuGeocoding(consumerLocation.getLat(),consumerLocation.getLng());
            if ("0".equals(resultJson.getString("status")) &&
                    null != resultJson.getJSONObject("result") &&
                    null != resultJson.getJSONObject("result").getJSONObject("addressComponent")) {
                JSONObject addressComponent = resultJson.getJSONObject("result").getJSONObject("addressComponent");
                String province = addressComponent.getString("province");
                String city = addressComponent.getString("city");
                if (StringUtils.isEmpty(city)) {
                    city = province;
                }
                String citycode = consumerLocationService.getCityCodeByCityName(province, city, addressComponent.getIntValue("city_level"));
                String district = addressComponent.getString("district");
                String adCode = addressComponent.getString("adcode");
                String towncode = addressComponent.getString("town_code");
                String township = addressComponent.getString("town");
                if( StringUtils.isNotEmpty(city) ){
                    consumerLocation.setCity(city);
                }
                if( StringUtils.isNotEmpty(citycode) ){
                    consumerLocation.setCitycode(citycode);
                }
                if( StringUtils.isNotEmpty(district) ){
                    consumerLocation.setDistrict(district);
                }
                if( StringUtils.isNotEmpty(adCode) ){
                    consumerLocation.setAdcode(adCode);
                }
                if( StringUtils.isNotEmpty(towncode) ){
                    consumerLocation.setTowncode(towncode);
                }
                if( StringUtils.isNotEmpty(township) ){
                    consumerLocation.setTownship(township);
                }
                consumerLocationsMapper.updateById(consumerLocation);
                cnt++;
            }
        }
        log.info("共更新省市区{}条数据",cnt);
    }

    @ApiOperation("设备详情")
    @RequestMapping(value = "/getRegionCenter", method = RequestMethod.GET)
    public void getRegionCenter() {
        JSONObject resultJson = locationUtil.getBaiduRegion("中国","3");
        if ("0".equalsIgnoreCase(resultJson.getString("status"))) {
            JSONArray districts = resultJson.getJSONArray("districts");
            if (ObjectUtil.isNotEmpty(districts)){
                JSONArray jsonArray = new JSONArray();
                jsonArray.set(0,districts.get(0));
                this.getSubStrict(jsonArray,"0","","","","");
            }
        }
    }

    private void getSubStrict(JSONArray districts, String padcode,String pathCode,String provinceName,String cityName,String districtName){
        if( ObjectUtil.isNotEmpty(districts) ){
            for (int i = 0; i < districts.size(); i++) {
                JSONObject jsonObject = districts.getJSONObject(i);
                String level = jsonObject.getString("level");
                String code = jsonObject.getString("code");
                String name = jsonObject.getString("name");
                String sql = "INSERT INTO t_baidu_region(adcode,padcode,adname,center,level,pathcode)VALUES('%s','%s','%s','%s',%s,'%s')";
                if ("1".equals(level)){
                    provinceName = name;
                    //pathCode = padcode+"|"+code;
                    double[] latLng = locationUtil.baiDuUrlGeocoding(provinceName);
                    System.out.println(String.format(sql,code,"",name,latLng[0]+","+latLng[1],level,padcode+"|"+code));
                }else if( "2".equals(level) ){ //城市
                    cityName = name;
                    //pathCode = pathCode+"|"+code;
                    double[] latLng = locationUtil.baiDuUrlGeocoding(provinceName+cityName);
                    System.out.println(String.format(sql,code,padcode,name,latLng[0]+","+latLng[1],level,padcode+"|"+code));
                }else if ("3".equals(level)){ //区
                    districtName = name;
                    //pathCode = pathCode+"|"+code;
                    double[] latLng = locationUtil.baiDuUrlGeocoding(provinceName+cityName+districtName);
                    System.out.println(String.format(sql,code,padcode,name,latLng[0]+","+latLng[1],level,padcode+"|"+code));
                }else if ("4".equals(level)){//街道
                    double[] latLng = locationUtil.baiDuUrlGeocoding(provinceName+cityName+districtName+name);
                    System.out.println(String.format(sql,code,padcode,name,latLng[0]+","+latLng[1],level,pathCode+"|"+code));
                }
                JSONArray subDistricts = jsonObject.getJSONArray("districts");
                if(ObjectUtil.isNotEmpty(subDistricts)){
                    this.getSubStrict(subDistricts,code,pathCode+"|"+code,provinceName,cityName,districtName);
                }
            }
        }
    }

    @ApiOperation("补充客户户号缺失信息")
    @RequestMapping(value = "/handleConsumerSubsData", method = RequestMethod.GET)
    public void handelConsumerData(@RequestParam("spId") String spId){
        log.info("handelConsumerData:处理开始");
        LambdaQueryWrapper<Consumer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Consumer::getSpId,spId);
        queryWrapper.eq(Consumer::getIsDeleted,false);
        queryWrapper.eq(Consumer::getCustName,"");
        queryWrapper.and(q->{q.isNotNull(Consumer::getSubsCode).ne(Consumer::getSubsCode, Constants.STR_EMPTY);});
        List<Consumer> consumers = consumerService.getBaseMapper().selectList(queryWrapper);
        for (Consumer consumer:consumers){
            log.info("开始处理consumer的数据：{}",JSONObject.toJSONString(consumer));
            spId = consumer.getSpId();
            spId = dictionaryService.selectNewAsstSpMapping(spId);
            log.info("createOrderConsumerBindImei current use spId:{}",spId);

            String subsCode = consumer.getSubsCode();
            VccUserRseponse vccUser = consumerService.getVccUser(subsCode,spId,"");
            if (vccUser==null) {
                log.info("户号:" + subsCode + "vcc未查到");
                continue;
            }
            DictionaryItemRespDTO custTypeDict = holder.getDictionaryInMap(Constants.CUST_TYPE_ENUM).get(vccUser.getCustType());
            consumer.setSubsCode(vccUser.getSubsCode());
            consumer.setCustName(vccUser.getCustName());
            consumer.setCustAddress(vccUser.getCustAddress());
            consumer.setCustPhone(vccUser.getCustPhone());
            consumer.setCustType(custTypeDict.getName());
            consumer.setCustTypeCode(vccUser.getCustType());
            consumer.setCustStatus(CustStatusEnum.getCustStatusName(vccUser.getCustStatus()));

            String orgCode = "";
            if (!spId.equals(ApplicationUtils.getHeaderSpId())) {
                CompanyEntry companyEntry = companyService.getBaseMapper().selectById(ApplicationUtils.getHeaderSpId());
                if (companyEntry != null && !companyEntry.getIsDeleted() &&
                        !org.springframework.util.StringUtils.isEmpty(companyEntry.getCode())) {
                    orgCode = companyEntry.getCode();
                }
                consumer.setOrgCode(orgCode);
            }
            if (StringUtils.isNotEmpty(vccUser.getCustAddress()) && (null==consumer.getPositionLon() || null==consumer.getPositionLat() ||
                    consumer.getPositionLat()<=0 || consumer.getPositionLon()<=0)){
                String preAddr = "";
                try {
                    Dictionary dictionary = dictionaryService.selectValueByAlias(orgCode);
                    preAddr = dictionary.getDescription();
                }catch (Exception e){
                    log.info(e.getMessage());
                }
                double[] latLng = locationUtil.baiDuUrlGeocoding(preAddr+vccUser.getCustAddress());
                consumer.setPositionLon(latLng[0]);
                consumer.setPositionLat(latLng[1]);
            }
            consumerService.getBaseMapper().updateById(consumer);

            consumerLocationService.updateConsumerLocation(consumer);
        }
        log.info("handelConsumerData:处理结束");
    }
}
